<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.11.0/qs.js"></script>
</head>

<body>

  <button>点击发送 GET 请求</button>
  <button>点击发送 POST 请求</button>
  <button>点击发送 PUT 请求</button>
  <button>点击发送 DELETE 请求</button>

  <script>

    // 直接在形参解构赋值 method params data 指定默认值
    function axios ({ url, method = 'get', params = {}, data = {} }) {
      return new Promise((resolve, reject) => {

        // 处理query参数
        // 根据params对象生成查询参数字符串: {a:1 ,b:2} =>a =1 & b =2
        const queryStr = Qs.stringify(params)
        // 如果有值  拼接到url
        if (queryStr) url += '?' + queryStr
        // 将请求方式都转为大写 方便判断是哪个请求方式
        method = method.toUpperCase()
        const xhr = new XMLHttpRequest()
        // 设置请求信息
        xhr.open(method, url)
        // 绑定监听
        xhr.onreadystatechange = () => {
          // 请求成功
          if (xhr.readyState === 4) {
            const status = xhr.status
            if (status >= 200 && status <= 299) {
              // 创建response对象
              const response = {
                // 将请求头转为JSON数据
                data: JSON.stringify(xhr.responseText),
                status,
                statusText: xhr.statusText
              }
              // 指定为成功的value
            } else {
              // 请求失败
              // 创建error对象
              const error = new Error('请求出错', status)
              // 指定为失败的reason
              reject(error)
            }
          }
        }

        // 处理body参数
        // 发送请求
        if (method === 'GET') {
          xhr.send() // get请求没有请求体参数
        } else {
          // 指定相应的请求头
          xhr.setRequestHeader('Content-Type', 'application/json')
          // 指定json格式的请求体
          xhr.send(JSON.stringify(data))
        }
      })
    }


    // 封装axios的静态方法
    axios.get = (url, config) => {
      return axios({ ...config, url, method: 'GET' })
    }
    axios.delete = (url, config) => {
      return axios({ ...config, url, method: 'DELETE' })
    }

    axios.post = (url, data, config) => {
      return axios({ ...config, url, method: 'post', data })
    }

    axios.put = (url, data, config) => {
      return axios({ ...config, url, method: 'put', data })
    }

  </script>

  <script>

    // 测试自定义的axios
    const btns = document.querySelectorAll('button')

    // 获取
    btns[0].onclick = async () => {
      try {
        const response = await axios.get('http://localhost:3000/movie', { params: { id: 2, name: '大话西游' } })
        console.log(response);
      } catch (error) {
        console.log(error);
        alert(error.message)
      }
    }

    // 添加
    btns[1].onclick = async () => {
      const response = await axios.post('http://localhost:3000/movie', { name: 'AA2', director: 'BB2' })
      console.log(response.data)
    }

    // 更新 
    btns[2].onclick = async () => {
      const response = await axios.put('http://localhost:3000/movie/8', { name: '野外生存记9', director: '贝爷9' })
      console.log(response.data)
    }

    // 删除
    btns[3].onclick = async () => {
      const response = await axios.delete('http://localhost:3000/movie/8')
      console.log(response.data)
    }



  </script>


</body>

</html>